// pages/material/index.js
const controllers = require('../controllers/controllerIndex.js').controller;
const BASE_URL = require('../../utils/kzj.request.js').url;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    src1:" https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/my/img/my_but_15.png",
    src2:" https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/image/my/img/my_but_26.png",
    list: [],
    bulletImg:"",
    dialogVisible: false,
    dialogVisible2:false,
    dialogVisible3:false,
    tempVideo:'',
    videoSrc:'',
    bulletUpload:{
      image: '',
      state: 0,
      goodsId: '',
      name: '',
      url: '',
      link:"",
      ids:""
    },
    selItem: {
      image: '',
      state: 0,
      goodsId: '',
      name: '',
      url: '',
      link:"",
      ids:""
    },
    defaultImg:"https://xinlingshoushangquan.oss-cn-shenzhen.aliyuncs.com/account/20210325/824701398040969216.gif",
    states: [
      {
        value: 0,
        text: '不跳转'
      },
      {
        value: 1,
        text: '商品/拼团'
      },
      // {
      //   value: 2,
      //   text: '外链'
      // },
      {
        value: 4,
        text: '优惠券'
      },
      {
        value: 3,
        text: 'vip卡'
      }
    ],
    goods: [
      '商品1',
      '商品2'
    ],
    chooseProduct: [],
    saving: false,
    chooseCoupon:""
  },
  onLoad: function (options) {
    this.shopRotationImg()
    this.getPoster()
  },
  onShow: function () {
    var that = this;
    var chooseProduct = that.data.chooseProduct;
    let chooseCoupon = that.data.chooseCoupon;
    let chooseCard = that.data.chooseCard;
    console.log('onShow--chooseProduct==', chooseProduct);
    if (chooseProduct && chooseProduct.length) {
      that.data.selItem.goodsId = chooseProduct[0].id;
      that.data.selItem.name = chooseProduct[0].name;
      that.data.bulletUpload.ids = chooseProduct[0].id;
      that.data.bulletUpload.name = chooseProduct[0].name;
      that.setData({
        selItem: that.data.selItem,
        bulletUpload: that.data.bulletUpload
      })
    }
    if (chooseCoupon) {
      console.log("执行")
      that.data.selItem.ids = chooseCoupon.ids;
      that.data.selItem.name = chooseCoupon.name;
      that.data.selItem.url = "/pages/Mall/Coupondetail";
      that.data.selItem.state = 4;
      that.data.bulletUpload.ids = chooseCoupon.ids;
      that.data.bulletUpload.name = chooseCoupon.name;
      that.data.bulletUpload.url = "/pages/Mall/Coupondetail";
      that.data.bulletUpload.state = 4;
      that.setData({
        selItem: that.data.selItem,
        bulletUpload: that.data.bulletUpload
      })
    }
    if (chooseCard) {
      console.log("执行")
      that.data.selItem.ids = chooseCard.ids;
      that.data.selItem.name = chooseCard.name;
      that.data.selItem.state = 3;
      that.data.selItem.url = "/pages/my/vip/info/VIPCardInfo";
      that.data.bulletUpload.ids = chooseCard.ids;
      that.data.bulletUpload.name = chooseCard.name;
      that.data.bulletUpload.state = 3;
      that.data.bulletUpload.url = "/pages/my/vip/info/VIPCardInfo";
      that.setData({
        selItem: that.data.selItem,
        bulletUpload: that.data.bulletUpload
      })
    }
  },

  switchDialog(e) {
    console.log('switchDialog--e==', e);
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type === "new") {
      that.data.dialogVisible = true;
      that.data.selItem = {};
    } else if (type === "cancel") {
      that.data.dialogVisible = false;
      that.data.selItem = {};
    } else  if (type === "edit") {
      var index = e.currentTarget.dataset.index;
      that.data.dialogVisible = true;
      that.data.selItem = that.data.list[index];
    }
    that.setData({
      dialogVisible: that.data.dialogVisible,
      selItem: that.data.selItem,
      saving:false
    })
  },
  switchDialog2(e) {
    console.log('switchDialog--e==', e);
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type === "new") {
      that.data.dialogVisible2 = true;
      that.data.bulletUpload = {};
    } else if (type === "cancel") {
      that.data.dialogVisible2 = false;
      that.data.bulletUpload = {};
    } else  if (type === "edit") {
      var index = e.currentTarget.dataset.index;
      that.data.dialogVisible2 = true;
      that.data.bulletUpload = that.data.bulletUpload;
    }
    that.setData({
      dialogVisible2: that.data.dialogVisible2,
      bulletUpload: that.data.bulletUpload
    })
  },
 

  delImg(e) {
    var that = this;
    const id = e.currentTarget.dataset.id;
    const shopId = wx.getStorageSync('shopId');
    if (that.data.saving) {
      return;
    }
    that.data.saving = true;
    wx.showLoading();
    controllers.delImg({ id, shopId }).then(res => {
      console.log('delImg--res==', res);
      const { code, data, desc } = res;
      that.data.saving = false;
      that.setData({
        dialogVisible: false,
        selTtem: {}
      })
      that.shopRotationImg();
      that.getPoster()
      wx.hideLoading();
    }).catch(res => {
      that.data.saving = false;
      wx.hideLoading();
    })
  },
  shopRotationImg() {
    var that = this;
    const params = {
      shopId:wx.getStorageSync('shopId'),
      type: 6
    };
    controllers.shopRotationImg(params).then(res => {
      console.log('shopRotationImg--res==', res);
      const { code, data, desc } = res;
      that.setData({
        list: data.imgList,
        videoSrc: data.video,
      })
    })
  },
  updateShopIndex(params) {
    let value={}
    value.id=params.id
    value.image=params.image||''
    value.state=params.state
    value.name=params.name||''
    value.url=params.url||''
    var that = this;
    controllers.updateShopIndex(params).then(res => {
      console.log('updateShopIndex--res==', res);
      const { code, data, desc } = res;
      that.data.saving = false;
      that.setData({
        dialogVisible: false,
        selTtem: {}
      })
      that.shopRotationImg();
      wx.hideLoading();
    }).catch(res => {
      that.data.saving = false;
      wx.hideLoading();
    })
  },
  saveShopIndex(params) {
    var that = this;
    controllers.saveShopIndex(params).then(res => {
      console.log('saveShopIndex--res==', res);
      const { code, data, desc } = res;
      that.setData({
        dialogVisible: false,
        selTtem: {},
        saving: false
      })
      that.shopRotationImg();
      wx.hideLoading();
    }).catch(res => {
      that.data.saving = false;
      wx.hideLoading();
    })
  },
  sub() {
    var that = this;
    var selItem = that.data.selItem;
    var showToast = false;
    var title = '';
    var params = { ...selItem };
    console.log('sub--params==', params);
    
    if (!selItem) {
      title = '请录入数据';
      showToast = true;
    } else if (!selItem.image) {
      title = '请上传图片';
      showToast = true;
    } else if (!selItem.state && selItem.state !== 0) {
      title = '请先进行跳转效果设置';
      showToast = true;
    } else if (selItem.state === 1) {
      params.url = '';
      if (!selItem.name || !selItem.goodsId) {
        title = '请选择跳转商品';
        showToast = true;
      }
    } 
    // else if (selItem.state === 2) {
    //   params.name = '';
    //   if (!selItem.url) {
    //     title = '请输入外链链接';
    //     showToast = true;
    //   }
    // }
    if (showToast) {
      wx.showToast({
        title,
        icon: 'none'
      })
      return;
    }
    if (that.data.saving) {
      return;
    }
    that.data.saving = true;
    wx.showLoading()
    if (params.id) {
      that.updateShopIndex(params);
    } else {
      that.saveShopIndex(params);
    }
  },

  sub2() {
    var that = this;
    var bulletUpload = that.data.bulletUpload;
    var showToast = false;
    var title = '';
    var params = { ...bulletUpload };
    console.log('sub--params==', params);
    if(this.data.bulletUpload.image){

    }else{
      this.setData({
        'bulletUpload.image':this.data.defaultImg
      })
    }
    if (!bulletUpload) {
      title = '请录入数据';
      showToast = true;
    } else if (!bulletUpload.state && bulletUpload.state !== 0) {
      title = '请先进行跳转效果设置';
      showToast = true;
    } else if (bulletUpload.state === 1) {
      params.url = '';
      if (!bulletUpload.name || !bulletUpload.ids) {
        title = '请选择跳转商品';
        showToast = true;
      }
    }
    if (showToast) {
      wx.showToast({
        title,
        icon: 'none'
      })
      return;
    }
    // if (that.data.saving) {
    //   return;
    // }
    // that.data.saving = true;
    wx.showLoading()
    this.setPoster()
    this.setData({
      dialogVisible2:false
    })
  },
  closeImg() {
    var that = this;
    that.data.selItem.image = '';
    that.setData({
      selItem: that.data.selItem
    })
  },

  closeImg2(){
    var that = this;
    that.data.bulletUpload.image = '';
    that.setData({
      bulletUpload: that.data.bulletUpload
    })
  },
  choose(){
    let that=this;
    wx.chooseImage({
      count:1,
      success (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: BASE_URL + '/api/img/uploadFile', 
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'Content-Type': 'application/form-data',
            'sessionId': wx.getStorageSync('token')
          },
          success (res){
            console.log('uploadFile--res==', res);
            let src=JSON.parse(res.data)
            that.data.selItem.image = src.data;
            that.setData({
              selItem: that.data.selItem
            })
          }
        })
      }
    })
  },
  choose2(){
    let that=this;
    wx.chooseImage({
      count:1,
      success (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: BASE_URL + '/api/img/uploadFile', 
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'Content-Type': 'application/form-data',
            'sessionId': wx.getStorageSync('token')
          },
          success (res){
            console.log('uploadFile--res==', res);
            let src=JSON.parse(res.data)
            that.data.bulletUpload.image = src.data;
            that.setData({
              bulletUpload: that.data.bulletUpload
            })
          }
        })
      }
    })
  },
  
  bindPickerChange(e) {
    console.log('bindPickerChange--e==', e);
    var value = parseInt(e.detail.value);
    that.data.selItem.goodsIndex = value;
    that.setData({
      selItem: that.data.selItem
    })
  },
  getInput(e) {
    var that = this;
    console.log('getInput--e==', e);
    var name = e.currentTarget.dataset.name;
    var value = e.detail.value;
    that.data.selItem[name] = value;
    that.setData({
      selItem: that.data.selItem
    })
  },
  changeType(e) {
    var that = this;
    var value = e.currentTarget.dataset.value;
    if (value !== that.data.selItem.states) {
      that.data.selItem.state = value;
      that.setData({
        selItem: that.data.selItem
      })
    }
  },
  changeType2(e) {
    var that = this;
    var value = e.currentTarget.dataset.value;
    if (value !== that.data.bulletUpload.states) {
      that.data.bulletUpload.state = value;
      that.setData({
        bulletUpload: that.data.bulletUpload
      })
    }
  },
  openPage(e) {
    var url = e.currentTarget.dataset.url;
    this.setData({
      chooseProduct:'',
      chooseCoupon:'',
      chooseCard:''
    })
    wx.navigateTo({
      url,
    })
  },


  //新增设置店铺页面弹窗
  setPoster(){
    let that=this
    let value=this.data.bulletUpload
    value.shopId=wx.getStorageSync('shopId')
    controllers.setPoster(value).then(res=>{
      wx.showToast({
        icon:"none",
        title: '添加/修改成功',
        duration:1500
      })
      wx.hideLoading();
      that.getPoster()
    })
  },

  //获取弹窗
  getPoster(){
    let shopId=wx.getStorageSync('shopId')
    controllers.getPoster({shopId:shopId}).then(res=>{
      this.setData({
        bulletImg:res.data
      })
    })
  },

  // 视频相关

  switchDialog3(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    if (type === "new") {
      that.data.dialogVisible3 = true;
      that.data.tempVideo = null;
    } else if (type === "cancel") {
      that.data.dialogVisible3 = false;
      that.data.tempVideo = null;
    } else  if (type === "edit") {
      that.data.dialogVisible3 = true;
      that.data.tempVideo = that.data.videoSrc;
    }
    that.setData({
      dialogVisible3: that.data.dialogVisible3,
      tempVideo: that.data.tempVideo
    })
  },
  closeVideo(){
    this.setData({
      tempVideo: null
    })
  },
  // 视频选择
  choose3(){
    let that=this;
    wx.chooseMedia({
      count:1,
      mediaType: ['video'],
      success (res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const size = res.tempFiles[0].size;
        console.log(size);
        const duration = res.tempFiles[0].duration;
        if(size>1024*1000*50){
          wx.showToast({
            title: '上传视频不可大于20M',
            icon:'none'
          })
          return
        }else if(duration>20){
          wx.showToast({
            title: '上传视频不可大于20秒',
            icon:'none'
          })
          return
        }
        that.uploadVideo(tempFilePath)
      }
    })
  },
  // 压缩并上传视频
  uploadVideo(path){
    // 压缩
    let that=this;
    wx.compressVideo({
      src:path,
      quality:'high',
      success(res){
        console.log(res);
        wx.showToast({
          title:'视频上传时间较长,请勿操作，耐心等待',
          icon: 'none',
          duration:2000,
        })
        let timer = setTimeout(()=>{
           wx.showLoading();
        },2000)

        // 上传
        wx.uploadFile({
          url: BASE_URL + '/api/img/uploadFile', 
          filePath: res.tempFilePath,
          name: 'image',
          formData: {
            'Content-Type': 'application/form-data',
            'sessionId': wx.getStorageSync('token')
          },
          success (res){
            wx.hideLoading();
            clearTimeout(timer)
    
            let src=JSON.parse(res.data)
            that.setData({
              tempVideo: src.data
            })
          }
        })

      }
    })

    
  },
  setvideo() {
    const tempVideo = this.data.tempVideo;
    
    if (!tempVideo) {
      wx.showToast({
        title:'请选择上传视频',
        icon: 'none'
      })
      return;
    }

    let value={
      shopId:wx.getStorageSync('shopId'),
      video:tempVideo
    }
    controllers.updateVideo(value).then(res=>{
      wx.showToast({
        icon:"none",
        title: '添加/修改成功',
        duration:1500
      })

      this.shopRotationImg();
      this.setData({
        dialogVisible3:false,
      })
    })
   
  },
  delVideo(){
    wx.showLoading();

    let value={
      shopId:wx.getStorageSync('shopId')
    }
    controllers.delVideo(value).then(res=>{
      this.shopRotationImg();

      wx.hideLoading();

      wx.showToast({
        icon:"none",
        title: '删除成功',
        duration:1500
      })
    })
  }
})